package com.ebupt.migu.restapi;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.ebupt.migu.common.pojo.IopMatch;
import com.ebupt.migu.common.pojo.IopMatchRep;
import com.ebupt.migu.common.response.Response;
import com.ebupt.migu.common.response.ResponseBean;
import com.ebupt.migu.common.util.PropertiesUtil;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;

/**
 * @author tz
 */
@Slf4j
public class IopMatchPost {

    private static PropertiesUtil prop = new PropertiesUtil();
    private static String iopUrl = prop.getValue("iopMatchUrl");
    private static String iopEnv = prop.getValue("iopEnv");
//    private static String esUrl = prop.getValue("esUrl");
    private static String index = "iop_application_";

    /**
     * iop标签验证
     */
    public boolean iopMatch(String iopTagId, String activityId, String phone, String uid) {
        // 测试环境直接返回匹配成功
        if (iopEnv.equals("false")) {
            return true;
        }
        try {
            if (!StringUtils.isEmpty(uid)) {
                // 通过uid去es反查对应手机号
                Calendar cal = Calendar.getInstance();
                cal.setTime(new Date());
                cal.add(Calendar.DAY_OF_YEAR, -2);
                String format = new SimpleDateFormat("yyyyMMdd").format(cal.getTime());
                String curIndex = index.concat(format);
                EsRestHttp er = new EsRestHttp();
                String str = er.search(curIndex,"uid",uid,1);
//                String str = HttpUtil.get(esUrl.concat(curIndex).concat("/_search?q=uid:").concat(uid));
                Object obj = new JSONObject(str).getByPath("hits.hits");
                if (ObjectUtil.isNotNull(obj)) {
                    JSONArray hits = (JSONArray)obj;
                    for (Object hit : hits) {
                        phone = String.valueOf(((JSONObject)hit).getByPath("_source.msisdn"));
                    }
                    log.info("es反查uid对应手机号：{}", phone);
                } else {
                    log.error("iop tag id:{}, activity id:{}, uid:{}", iopTagId, activityId, uid);
                    log.error("es索引{}不存在或者uid无对应手机号", curIndex);
                }
            }
            return !StringUtils.isEmpty(phone) && this.iopMatch(iopTagId, activityId, phone);
        } catch (Exception e) {
            log.error("iop tag id:{}, activity id:{}, uid:{}", iopTagId, activityId, uid);
            log.error("iop match interface error:{}", e.getMessage());
            return false;
        }
    }

    public boolean iopMatch(String iopTagId, String activityId, String phone) {
        // 测试环境直接返回匹配成功
        if (iopEnv.equals("dev")) {
            return true;
        }
        try {
            IopMatch im = new IopMatch(iopTagId, phone, activityId);
            RestHttpPost post = new RestHttpPost();
            Response<String> response = post.doRest(im, iopUrl);
            if ("0000".equals(response.getHead().getResponseCode())) {
                ResponseBean res = JSON.parseObject(response.getResponse(), ResponseBean.class);
                if (null != res.getData()) {
                    IopMatchRep rep = JSON.toJavaObject((JSON)res.getData(), IopMatchRep.class);
                    return rep.isExist();
                }
            }
            return false;
        } catch (Exception e) {
            log.error("iop tag id:{}, activity id:{}, msisdn:{}", iopTagId, activityId, phone);
            log.error("iop match interface error:{}", e.getMessage());
            return false;
        }
    }

    public static void main(String[] args) {
        String uid = "15640553218520349154091";
        IopMatchPost ip = new IopMatchPost();
        boolean b = ip.iopMatch("123", "456", "", uid);
    }

}
